package com.example.coursedesign.ui.notifications;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.coursedesign.R;
import com.example.coursedesign.dao.UserDao;
import com.example.coursedesign.entity.User;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import androidx.lifecycle.ViewModelProvider;
public class EditProfileActivity extends AppCompatActivity {


    private UserViewModel userViewModel;
    private static final String TAG = "EditProfileActivity";
    private User currentUser;
    private Map<String, String> changedFields = new HashMap<>();
    private UserDao userDao = new UserDao();
    private static final int CAMERA_REQUEST = 100;
    private static final int GALLERY_REQUEST = 200;
    private static final int PERMISSION_REQUEST_CODE = 300;
    private Uri selectedImageUri = null; // 用于存储所选图片的 URI

    // 固定账号信息
    private static final String FIXED_ACCOUNT = "user123"; // 替换为实际的固定账号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_profile);

        // 启用返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        // 启动 AsyncTask 来加载用户信息
        new LoadUserTask().execute(FIXED_ACCOUNT);

        // 设置头像选择按钮监听器
        setAvatarSelectionListeners();

        // 初始化 ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        // 启动 AsyncTask 来加载用户信息
        new LoadUserTask().execute(FIXED_ACCOUNT);

        // 设置头像选择按钮监听器
        setAvatarSelectionListeners();
    }

    private void setAvatarSelectionListeners() {
        Button btnCamera = findViewById(R.id.button_camera);
        Button btnGallery = findViewById(R.id.button_gallery);

        if (btnCamera != null && btnGallery != null) {
            btnCamera.setOnClickListener(v -> checkPermissionsAndOpenCamera());
            btnGallery.setOnClickListener(v -> openGallery());
        }
    }

    private void checkPermissionsAndOpenCamera() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        } else {
            openCamera();
        }
    }

    private void openCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        } else {
            Toast.makeText(this, "无法打开相机", Toast.LENGTH_SHORT).show();
        }
    }

    private void openGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (galleryIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        } else {
            Toast.makeText(this, "无法打开相册", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                Toast.makeText(this, "请授予相机和存储权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_REQUEST && data != null) {
                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                updateAvatar(imageBitmap);
            } else if (requestCode == GALLERY_REQUEST && data != null) {
                selectedImageUri = data.getData();
                try {
                    Bitmap imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
                    updateAvatar(imageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "无法加载图片", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void updateAvatar(Bitmap bitmap) {
        ImageView ivTouxiang = findViewById(R.id.iv_avatar);
        Glide.with(this)
                .load(R.drawable.a)
                .apply(RequestOptions.circleCropTransform())
                .into(ivTouxiang);

        // 将图片转换为Base64字符串并保存到changedFields
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
        changedFields.put("avatar", encoded);
    }

    private class LoadUserTask extends AsyncTask<String, Void, User> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.d(TAG, "Loading user information...");
        }

        @Override
        protected User doInBackground(String... params) {
            String account = params[0];
            return userDao.findUserByAccount(account);
        }

        @Override
        protected void onPostExecute(User user) {
            super.onPostExecute(user);

            if (user == null) {
                Log.e(TAG, "Failed to load user for account: " + FIXED_ACCOUNT);
                Toast.makeText(EditProfileActivity.this, "未能找到固定账号的信息", Toast.LENGTH_SHORT).show();
                finish(); // 关闭当前活动，返回上一页
                return;
            }

            currentUser = user;
            updateUI(currentUser);
            setClickListeners();

            Log.d(TAG, "User loaded successfully: " + currentUser.toString());
        }
    }

    private void setClickListeners() {
        Button btnSave = findViewById(R.id.btn_edit);
        if (btnSave != null && currentUser != null) {
            btnSave.setOnClickListener(v -> {
                collectChangedUserInfo();

                if (!changedFields.isEmpty()) {
                    new UpdateUserTask().execute();
                } else {
                    Toast.makeText(EditProfileActivity.this, "没有任何更改", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void collectChangedUserInfo() {
        if (currentUser == null) {
            Toast.makeText(this, "无法获取用户信息，请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }

        changedFields.clear();

        EditText etNickname = findViewById(R.id.et_nickname);
        EditText etTel = findViewById(R.id.et_tel);
        EditText etPassword = findViewById(R.id.et_password);
        RadioGroup rgGender = findViewById(R.id.rg_gender);
        int selectedId = rgGender.getCheckedRadioButtonId();
        RadioButton rbSelected = findViewById(selectedId);
        String gender = rbSelected != null ? rbSelected.getText().toString() : "";

        checkAndCollectField(etNickname, currentUser.getName(), "name");
        checkAndCollectField(etTel, currentUser.getPhone(), "phone");
        checkAndCollectField(etPassword, currentUser.getPassword(), "password");

        if (!gender.equals(currentUser.getGender())) {
            changedFields.put("gender", gender);
        }

        Log.d(TAG, "Collected changed fields: " + changedFields.toString());
    }

    private void checkAndCollectField(EditText editText, String originalValue, String fieldName) {
        String newValue = editText.getText().toString();
        if (!newValue.equals(originalValue)) {
            changedFields.put(fieldName, newValue);
        }
    }

    private void updateUI(User user) {
        if (user == null) {
            return;
        }
        ImageView ivTouxiang = findViewById(R.id.iv_avatar);
        if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
            byte[] decodedBytes = Base64.decode(user.getAvatar(), Base64.DEFAULT);
            Glide.with(this)
                    .load(decodedBytes)
                    .apply(RequestOptions.circleCropTransform())
                    .into(ivTouxiang);
        }
        ((EditText)findViewById(R.id.et_nickname)).setText(user.getName());
        ((EditText)findViewById(R.id.et_tel)).setText(user.getPhone());
        ((EditText)findViewById(R.id.et_password)).setText(user.getPassword());

        RadioGroup rgGender = findViewById(R.id.rg_gender);
        if ("男".equals(user.getGender())) {
            rgGender.check(R.id.rb_male);
        } else if ("女".equals(user.getGender())) {
            rgGender.check(R.id.rb_female);
        } else {
            rgGender.clearCheck();
        }
    }

    private class UpdateUserTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(EditProfileActivity.this, "正在保存...", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            return userDao.updateUserPartially(currentUser, changedFields);
        }

        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
            if (success) {
                applyChangesToCurrentUser(changedFields);
                // 通过 ViewModel 更新 LiveData
                userViewModel.updateCurrentUser(currentUser);
                Intent resultIntent = new Intent();
                resultIntent.putExtra("updatedUser", currentUser);
                setResult(RESULT_OK, resultIntent);
                finish(); // 关闭当前活动
            } else {
                Toast.makeText(EditProfileActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void applyChangesToCurrentUser(Map<String, String> changes) {
        for (Map.Entry<String, String> entry : changes.entrySet()) {
            switch (entry.getKey()) {
                case "name":
                    currentUser.setName(entry.getValue());
                    break;
                case "phone":
                    currentUser.setPhone(entry.getValue());
                    break;
                case "password":
                    currentUser.setPassword(entry.getValue());
                    break;
                case "gender":
                    currentUser.setGender(entry.getValue());
                    break;
                case "avatar":
                    currentUser.setAvatar(entry.getValue());
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed(); // 返回上一个 Activity
        return true;
    }
}